<template>
  <div>
    <h3>商家管理 - 删除店铺</h3>
    <el-form :model="merchantDeleteDto" ref="merchantDeleteForm" label-width="120px" :rules="rules">
      <el-form-item label="选择店铺" prop="id">
        <el-select v-model="merchantDeleteDto.id" placeholder="请选择要删除的店铺">
          <el-option
              v-for="store in merchantList"
              :key="store.id"
              :label="store.shopName"
              :value="store.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="deleteStore">确认删除</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'; // 新增 ElMessageBox 导入

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 定义表单数据
const merchantDeleteDto = ref({
  id: null,
  userId: user?.id || null
});

// 存储店铺列表
const merchantList = ref([]);

// 表单验证规则
const rules = reactive({
  id: [
    { required: true, message: '请选择要删除的店铺', trigger: 'change' }
  ]
});

// 表单引用
const merchantDeleteForm = ref(null);

// 获取店铺列表
const selStore = async () => {
  try {
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取店铺列表失败');
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error);
    ElMessage.error('获取店铺列表失败，请稍后重试');
  }
};

// 定义删除店铺方法
const deleteStore = async () => {
  // 表单验证
  merchantDeleteForm.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请选择要删除的店铺');
      return;
    }

    // 使用 ElMessageBox.confirm 替代 ElMessage.confirm
    ElMessageBox.confirm('确定要删除该店铺吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 发送删除店铺请求
      axios.post(`${BASE_URL}/api/v1/merchant/delStore`, {
        id: merchantDeleteDto.value.id,
        userId: user?.id || null
      }, {
        withCredentials: true
      })
          .then(response => {
            if (response.data.code === 2000) {
              ElMessage.success('店铺删除成功');
              // 清空表单
              merchantDeleteDto.value = {
                id: null,
                userId: user?.id || null
              };
              // 重新获取店铺列表
              selStore();
            } else {
              ElMessage.error(response.data.msg || '删除店铺失败');
            }
          })
          .catch(error => {
            console.error('删除店铺失败:', error);
            ElMessage.error('删除店铺失败，请稍后重试');
          });
    }).catch(() => {
      // 取消操作
    });
  });
};

// 页面挂载时获取店铺列表
onMounted(() => {
  selStore();
});
</script>

<style scoped>
/* 样式保持不变 */
</style>